package com.example.demo02_simple_start.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 明文加密方式，即不加密
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // inMemoryAuthentication 开启内存中定义的用户
        auth.inMemoryAuthentication()
                .withUser("wangnian666")
                .password("666")
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //对静态资源放行，这种放行方式是不走 security 过滤器的
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()//拦截没有放行的所有请求
                .and()
                .formLogin()
                //设置登录页面为 /login.html 的时候，spring security会自动注册一个 post 请求的 /login.html 接口来处理登录逻辑
                .loginPage("/login.html")
                .permitAll()//放行登录相关的页面/接口
                .and()
                .csrf().disable();//关闭 csrf
    }
}
